﻿using System.Collections.Generic;

namespace Algoritmia.DataStructures.Trees 
{
    public class BinaryTree : IBinaryTree
    {
        public BinaryTree(IBinaryTree parent = null, IBinaryTree left = null, IBinaryTree right = null)
        {
            Parent = parent ?? this;
            AppendLeft(left);
            AppendRight(right);
        }

        #region Implementation of IBinaryTree

        public IEnumerable<IBinaryTree> Children()
        {
            if ( Left != null)
            {
                yield return Left;
            }
            if ( Right != null)
            {
                yield return Right;
            }
        }

        public IBinaryTree Left
        {
            get; set; 
        }

        public IBinaryTree Right
        {
            get;
            set;
        }

        public IBinaryTree Parent
        {
            get; set; }

        public bool IsLeft
        {
            get { return ReferenceEquals(Parent.Left, this); }
        }

        public bool IsRight
        {
            get { return ReferenceEquals(Parent.Right, this); }
        }

        public bool IsRoot
        {
            get { return ReferenceEquals(Parent, this); }
        }

        public void AppendLeft(IBinaryTree node)
        {
            Left = node;
            if ( node != null)
            {
                node.Parent = this;
            }
        }

        public void AppendRight(IBinaryTree node)
        {
            Right = node;
            if (node != null)
            {
                node.Parent = this;
            }
        }

        #endregion

    }

}
